package com.lg.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.UUID;

import org.apache.commons.io.FileUtils;

public class FileUtil {

	public static String[]  uploadFile(byte[] file, String filePath, String fileName) throws IOException {
		String path[]=new String[2];
		LocalDate today=LocalDate.now();
		File targetFile = new File(getDateStr(filePath,today.toString()));
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		String finalPath=getDateStr(filePath,today.toString(),fileName);
		FileOutputStream out = new FileOutputStream(finalPath);
		out.write(file);
		out.flush();
		out.close();
		path[0]=finalPath;//本地真实路径
		path[1]=getDateStr(today.toString(),fileName);//相对路径
		return path;
	}
	
	public static String getDateStr(String ...path ){
		String s="";
		for(String str:path){
			s+=str+"/";
		}
		return s;
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	public static void copyURLToFile(String httpUrl, String dir, String fileName){
		try {
			FileUtils.copyURLToFile(new URL(httpUrl), new File(dir+fileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}
	
	public static String getPrefix(String fileName){
        String prefix=fileName.substring(fileName.lastIndexOf("."));
        return prefix;
	}
	
    public static String FormetFileSize(long fileS) {//转换文件大小
	       DecimalFormat df = new DecimalFormat("#.00");
	       String fileSizeString = "";
	       if (fileS < 1024) {
	           fileSizeString = df.format((double) fileS) + "B";
	       } else if (fileS < 1048576) {
	           fileSizeString = df.format((double) fileS / 1024) + "K";
	       } else if (fileS < 1073741824) {
	           fileSizeString = df.format((double) fileS / 1048576) + "M";
	       } else {
	           fileSizeString = df.format((double) fileS / 1073741824) +"G";
	       }
	       return fileSizeString;
	    }
}
